/*
 * @Description: 元数据基础 增加、编辑 通用表单
 * @Author: Rfan
 * @Date: 2022-05-30 15:56:42
 * @LastEditTime: 2022-06-16 16:04:38
 */

import { Checkbox, Form, Radio, Select } from 'antd';
import { useEffect, useState } from 'react';
import { ILevel } from '@/interfaces/archiveType';
import { jsonClone } from '@/utils';
import { selectItemByKey } from '@/utils/list';
import { useMetadataInheritContext } from '../../../contexts/MetadataInheritContext';

const { Option } = Select;

interface IInheritFormProps {
  getFieldsLevel: (current: number, upper: number) => void;
}

const InheritForm = (props: IInheritFormProps) => {
  const { getFieldsLevel } = props;
  const { selectAT, selectLevel, levelMatedata, getLevelMetadata } = useMetadataInheritContext();
  const { levelList }: { levelList: ILevel[] } = selectAT || [];

  const [upperLevel, setUpperLevel] = useState<ILevel>({} as ILevel);

  useEffect(() => {
    if (selectLevel && selectLevel.level) {
      const _level = jsonClone(selectLevel) && jsonClone(selectLevel).level + 1;
      setUpperLevel(selectItemByKey(_level, levelList, 'level') as ILevel);
      getLevelMetadata(selectLevel.level);
      getFieldsLevel(selectLevel.level, upperLevel.level);
    }
  }, [selectLevel]);

  useEffect(() => {
    if (upperLevel && upperLevel.level) {
      getLevelMetadata(upperLevel.level);
      getFieldsLevel(selectLevel.level, upperLevel.level);
    }
  }, [upperLevel]);

  return (
    <>
      <Form.Item name="isValid" label="状态">
        <Radio.Group>
          <Radio value={0}>启用</Radio>
          <Radio value={1}>停用</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="层级" required>
        <Form.Item
          name="targetDataId"
          label={selectLevel.levelName}
          colon={false}
          rules={[{ required: true }]}
          required={false}
        >
          <Select>
            {(levelMatedata[selectLevel.level] || []).map((item: any) => (
              <Option key={item.id} value={item.id}>
                {item.field_desc}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form.Item>
      <Form.Item label="继承层级" required>
        <Form.Item
          name="ruleDataId"
          label={upperLevel.levelName}
          colon={false}
          rules={[{ required: true }]}
          required={false}
        >
          <Select>
            {(levelMatedata[upperLevel?.level] || []).map((item: any) => (
              <Option key={item.id} value={item.id}>
                {item.field_desc}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form.Item>
      <Form.Item name="isLinkage" label="数据联动" valuePropName="checked">
        <Checkbox>与继承字段联动</Checkbox>
      </Form.Item>
    </>
  );
};

export default InheritForm;
